package com.community.sqlapp.databaseConfiguration;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * AOP拦截器（自动切换数据源）
 */
@Aspect
@Component
public class DataSourceAspect {
    @Before("@annotation(com.community.sqlapp.databaseConfiguration.TargetDataSource)")
    public void switchDataSource(JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        TargetDataSource annotation = signature.getMethod().getAnnotation(TargetDataSource.class);

        // 获取方法参数中的dbName
        Object[] args = point.getArgs();
        if (args != null && args.length > 0 && args[0] instanceof String) {
            String dbName = (String) args[0];
            // 动态设置数据源key，格式为"db"+数据库序号
            String dataSourceKey = "db" + getDataSourceIndex(dbName);
            DynamicDataSourceContextHolder.setDataSourceKey(dataSourceKey);
            System.out.println("切换到数据源: " + dataSourceKey);
        } else {
            // 默认使用db1数据源
            DynamicDataSourceContextHolder.setDataSourceKey("db1");
            System.out.println("使用默认数据源: db1");
        }
    }

    private int getDataSourceIndex(String dbName) {
        // 这里可以根据实际数据库名称映射到对应的数据源序号
        if ("web_database".equals(dbName)) {
            return 2;
        }
        return 1; // 默认返回1
    }
    @Before("@annotation(targetDataSource)")
    public void switchDataSource(JoinPoint point, TargetDataSource targetDataSource) {
        Object[] args = point.getArgs();
        String dbName = (args != null && args.length > 0) ? args[0].toString() : "db1";
        String dataSourceKey = "db" + ("web_database".equals(dbName) ? 2 : 1);
        DynamicDataSourceContextHolder.setDataSourceKey(dataSourceKey);
    }
}
